﻿#include "SerialTlv.h"
#include <QSerialPort>
#include <QEventLoop>
#include <QTimer>
#include <QDebug>


SerialTlv::SerialTlv(QObject *parent)
    : ICom(parent)
    , m_serialPort(new QSerialPort(this))
{
    connect(m_serialPort, &QSerialPort::readyRead, this, [=](){
        onReadyRead(m_serialPort->readAll());
    });
    connect(m_serialPort, &QSerialPort::errorOccurred, this, [=](QSerialPort::SerialPortError error){
        if (error != QSerialPort::SerialPortError::NoError) {
            emit errorOccurred(m_serialPort->errorString());
            close();
        }
    });
}

SerialTlv::~SerialTlv()
{
    close();
}

void SerialTlv::open()
{
    m_serialPort->setDataBits(QSerialPort::Data8);
    m_serialPort->setParity(QSerialPort::NoParity);
    m_serialPort->setStopBits(QSerialPort::OneStop);
    m_serialPort->setFlowControl(QSerialPort::NoFlowControl);

    if (m_serialPort->open(QIODevice::ReadWrite)) {
        emit opened();
    }
}

void SerialTlv::close()
{
    if (m_serialPort->isOpen()) {
        m_serialPort->close();
        emit closed();
    }
}

void SerialTlv::IWrite(const QByteArray &data)
{
    m_serialPort->write(data);
}

bool SerialTlv::isOpen() const
{
    return m_serialPort->isOpen();
}

QString SerialTlv::hwName() const
{
    return tr("Serial");
}

QString SerialTlv::portName() const
{
    return m_serialPort->portName();
}

uint32_t SerialTlv::baudRate() const
{
    return m_serialPort->baudRate();
}

void SerialTlv::setAttr(const QString &portName, uint32_t baudRate)
{
    m_serialPort->setPortName(portName);
    m_serialPort->setBaudRate(baudRate);
}

SerialTlv* SerialTlv::instance()
{
    static SerialTlv* inst = nullptr;
    if (!inst) {
        inst = new SerialTlv();

        // 跨线程通讯必须注册：
        qRegisterMetaType<QSerialPort::SerialPortError>("QSerialPort::SerialPortError");
    }
    return inst;
}

